package com.hi.hiparty.solr;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrInputDocument;

import com.hi.hiparty.entity.Party;

public class SolrUtils {

	private static final Log logger = LogFactory.getLog(SolrUtils.class);

	private static final SimpleDateFormat DATE_SEARCH_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

	public static void deleteAllByFieldName(String pk) throws SolrServerException, IOException {
		SolrServerHolder.server.deleteByQuery(pk + ":*");
		SolrServerHolder.server.commit();
	}

	public static void deleteAllByFieldNameAndValue(String fieldName, String value) throws SolrServerException,
			IOException {
		SolrServerHolder.server.deleteByQuery(fieldName + ":" + value);
		SolrServerHolder.server.commit();
	}

	public static int addParty(Party doc) throws SolrServerException, IOException {
		if (0 != SolrServerHolder.server.addBean(doc).getStatus())
			return -1;
		if (0 != SolrServerHolder.server.commit().getStatus())
			return -1;
		return 0;
	}

	// 应用场景，更改登录用户坐标
	public static int addPartys(List<Party> partyList) throws SolrServerException, IOException {
		if (0 != SolrServerHolder.server.addBeans(partyList).getStatus())
			return -1;
		if (0 != SolrServerHolder.server.commit().getStatus())
			return -1;
		return 0;
	}

	public static HttpSolrServer add(SolrInputDocument doc) throws SolrServerException, IOException {
		SolrServerHolder.server.add(doc);
		SolrServerHolder.server.commit();
		return SolrServerHolder.server;
	}

	public static void commit() throws SolrServerException, IOException {
		SolrServerHolder.server.commit();
	}

	public static void optimize() throws SolrServerException, IOException {
		SolrServerHolder.server.optimize();
	}

	// 使用HotsolrQuery的设置来查询
	public static QueryResponse query(SolrQuery params) throws SolrServerException {
		return SolrServerHolder.server.query(params);
	}

	public static Result<Party> getPartyListByQueryPara(PartyQuery pQuery) {
		PartySolrQuery query = new PartySolrQuery();
		query.set("version", "2.2");

		// 配置分页
		query.setStart(pQuery.getStartRow());
		query.setRows(pQuery.getEndRow());
		query.setQuery("*:*");
		
		// 处理位置查询
		if (null != pQuery.getPosType() && null != pQuery.getLatlon()) {
			query.addFilterQuery("{!geofilt}");
			if (pQuery.getPosType() == PartyQuery.POS_TYPE_PARTY)
				query.setParam("sfield", "partyPos");
			if (pQuery.getPosType() == PartyQuery.POS_TYPE_USER)
				query.setParam("sfield", "userPos");
			query.setParam("pt", "" + pQuery.getLatlon());
			query.setParam("d", "" + pQuery.getRadius());
			// 排列顺序待定
			query.addSortField("geodist()", ORDER.desc);
		}

		// 选择发起人性别
		if (0 != pQuery.getCreatorSex()) {
			query.setQuery("creatorSex:" + pQuery.getCreatorSex());
		}

		// 按发布时间选择
		if (null != pQuery.getMinCreateTime()) {
			query.addRangeFilter("createTime", "*", DATE_SEARCH_FORMAT.format(pQuery.getMinCreateTime()));
		}

		Result<Party> rs = new Result<Party>();
		try {
			QueryResponse solrRsp = query(query);
			List<Party> partys = solrRsp.getBeans(Party.class);
			rs.setList(partys);
			rs.setCount(solrRsp.getResults().getNumFound());
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg(e.getMessage());
			// e.printStackTrace();
		}

		return rs;
	}

	static class SolrServerHolder {
		static HttpSolrServer server = null;
		static {
			// 此处可以再改进，加入java轮询程序。不通过nginx、或apache 轮询
			server = new HttpSolrServer("http://127.0.0.1:8983/solr");
			server.setConnectionTimeout(100);
			server.setDefaultMaxConnectionsPerHost(100);
			server.setMaxTotalConnections(100);
		}
	}
}
